package com.example.downloader.model;

import android.os.AsyncTask;
import android.util.Log;

/**
 * Created by Administrator on 2017/9/22 0022.
 */

public abstract class DownloadTask<Result> extends AsyncTask<String, Integer, Result> {
    private final DownloadCallback<Result> mCallback;
    static final int STARTED = 0;
    protected static final int PROGRESS = 1;
    private volatile boolean mError;

    public DownloadTask(DownloadCallback callbck) {
        mCallback = callbck;
    }

    public DownloadCallback<Result> getProgressCallback() {
        return mCallback;
    }

    @Override
    protected final void onPreExecute() {
        mCallback.onWaiting();
    }

    @Override
    protected final void onProgressUpdate(Integer... values) {
        switch (values[0]) {
            case STARTED:
                mCallback.onStarted();
                break;
            case PROGRESS:
                mCallback.onLoading(values[1], values[2]);
                break;

        }
    }

    @Override
    protected final Result doInBackground(String... params) {
        publishProgress(STARTED);
        Result result = null;
        try {
            result = doInBackground2(params);

        } catch (Throwable throwable) {
            mError = true;
            throwable.printStackTrace();
        }
        return result;
    }

    protected abstract Result doInBackground2(String... params) throws Throwable;

    @Override
    protected final void onPostExecute(Result result) {
        if (mError) {
            mCallback.onError();
            return;
        }

        mCallback.onSuccess(result);
    }


    @Override
    protected final void onCancelled() {
        mCallback.onCancelled();
    }
}
